import axios from 'axios'
import store from '@/store'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 登录时请求头携带token
    const token = store.state.user.token;
    // console.log(token);
    if (token) {
      config.headers.token = token;
    }
    return config
  }
)

// response interceptor
service.interceptors.response.use(

  // // 响应拦截器函数：得到响应之后触发的函数
  (response) => {
    // 请求成功
    // console.log(response.data)
    if (response.data.code === 20000 || response.data.code === 200) {
      //返回成功的数据
      return response.data;
    } 
    // else if (response.data.code === 20001) {
    //   // token过期
    //   // localStorage.removeItem('token_key');
    //   // window.location.href = '/';
		// 	return Promise.reject(service.interceptors.response);
    // }
    else {
      // 说明功能失败，没有数据，返回失败的原因
      const errorMsg = response.data.data || response.data.message
      alert(errorMsg);
      return Promise.reject(errorMsg);
    }
  },
  (error) => {
    // 请求失败
    alert(error.message);
    return Promise.reject(error);
  }
)


export default service
